package bit.pja.wolfkill.Service;


import bit.pja.wolfkill.aop.Flag;
import bit.pja.wolfkill.entity.*;
import io.swagger.models.auth.In;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;


@Service
public class RoomService {

    private final Map<Integer, Room> roomFactory = new HashMap<>();
    private final int MAX_ROOMS = 10000;

    @Autowired
    private GameService gameService;

    public void clear() {
        roomFactory.clear();
    }

    public Room getRoom(Integer roomId) throws Exception {
        if (roomFactory.containsKey(roomId)) {
            return roomFactory.get(roomId);
        }
        throw new Exception("没有该房间");
    }


    public Room createRoom(Integer userId, RolesParam rolesParam) {
        Integer roomId = new Random().nextInt(100);

        if (roomFactory.containsKey(roomId)) {
            Room room = roomFactory.get(roomId);
            if (room.getCreatedTime().getTime() - new Date().getTime() < 6*3600*1000) {
                return createRoom(userId, rolesParam);
            } else {
                room = new Room(roomId, userId, rolesParam);
                roomFactory.put(roomId, room);
                return room;
            }
        } else {
            Room room = new Room(roomId, userId, rolesParam);
            roomFactory.put(roomId, room);
            return room;
        }
    }

    public Room createRoom(Integer userId, RolesParam rolesParam, Integer roomId) throws Exception{

        if (roomFactory.containsKey(roomId)) {
           throw new Exception("房间ID已存在，请更换ID");
        }

        Room room = new Room(roomId, userId, rolesParam);
        roomFactory.put(roomId, room);
        return room;

    }


    public Room join(Integer userId, Integer roomId) throws Exception{
        Room room = getRoom(roomId);
        return join(userId, room);
    }

    public Room join(Integer userId, Room room) throws Exception{
        List<User> roomUsers = room.getUsers();
        for (User user : roomUsers) {
            if(user.getId().equals(userId)) {
                return room;
            }
        }
        if (room.getSize() > room.getUsers().size()) {
            User user = new User(userId);
            roomUsers.add(user);
            user.setIndex(roomUsers.indexOf(user));
            return join(userId, room);
        } else {
            throw new Exception("房间人数已满");
        }
    }

    public Room quit(Integer userId, Integer roomId) throws Exception{
        Room room = getRoom(roomId);
        return quit(userId, room);
    }

    public Room quit(Integer userId,  Room room) throws Exception{
        List<User> roomUsers = room.getUsers();
        for (User user : roomUsers) {
            if(user.getId().equals(userId)) {
                roomUsers.remove(user);
                if(userId.equals(room.getHostID())) {
                    if (!roomUsers.isEmpty()) {
                        room.setHostID(roomUsers.get(0).getId());
                    }
                }
                return room;
            }
        }
        throw new Exception("用户不在房间");
    }



    public void closeRoom(Integer userId, Integer roomId) throws Exception{

    }

    public Room begin(Integer userId, Integer roomId) throws Exception{
        Room room = getRoom(roomId);
        validateHost(userId, room);
        if(room.getUsers().size() < room.getSize()) {
            throw new Exception("在场人数小于开始人数");
        }
        if(room.getState() != Room.STATE_READY) {
            throw new Exception("当前房间不能开始游戏，请检查游戏是否已经开始或结束");
        }
        Game game = new Game(room);
        room.setState(Room.STATE_BEGIN);
        gameService.beginAGame(game);
        return room;
    }

    private void validateHost(Integer userId, Room room) throws Exception{
        if (userId.equals(room.getHostID())) {
            return ;
        }
        throw new Exception("用户不是房主");
    }

    public Room process(Integer roomId,  PutParams params) throws Exception{
        Room room = getRoom(roomId);
        if(room.getState() == 0) {
            throw new Exception("游戏还没有开始，请先开始游戏");
        }
        if(room.getState() == 2) {
            throw new Exception("游戏已经结束，请勿操作");
        }
        if(room.getGame().isOver() == true) {
            room.setState(Room.STATE_END);
            process(roomId, params);
        }
        Game game = room.getGame();
        gameService.paramsValidate(game, params);
        gameService.insertRecord(game, params);
        return room;
    }

    public int getUserIndex(Room room, Integer userId) throws Exception{
        for (User user : room.getUsers()) {
            if (userId.equals(user.getId())) {
                return room.getUsers().indexOf(user);
            }
        }
        return -1;
    }

    public int getUserIndex(Integer roomId, Integer userId) throws Exception{
        Room room = getRoom(roomId);
        return getUserIndex(room, userId);
    }

    public User getUser(Room room, Integer index) throws Exception{
        List<User> users = room.getUsers();
        if (index < 0 || index >= users.size()) {
            throw new Exception(String.format("序号为%d的玩家不存在", index));
        }

        return users.get(index);
    }



}
